package cn.virens.server.netty_udp;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.common.utils.number.ByteUtil;
import cn.virens.server.netty_udp.packet.UdpReadPacket;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.DatagramPacketDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;

public class UDPServerPacketDecoder extends MessageToMessageDecoder<DatagramPacket> {
	private static final Logger logger = LoggerFactory.getLogger(DatagramPacketDecoder.class);

	private final UDPServerPacketHandler serverPacketHandler;

	public UDPServerPacketDecoder(UDPServerPacketHandler serverPacketHandler) {
		this.serverPacketHandler = serverPacketHandler;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
		logger.debug("接收({})数据:{}", msg.sender(), ByteBufUtil.hexDump(msg.content()));

		byte[] bs = msg.content().array();

		UDPServerChannel uDPServerChannel = serverPacketHandler.warp(mac(bs), msg);
		uDPServerChannel.heatTimes().incrementAndGet();
		uDPServerChannel.heatIdle().getAndSet(0);

		UdpReadPacket readPacket = new UdpReadPacket(uDPServerChannel);
		readPacket.setData(data(bs));
		readPacket.setSeq(bs[9]);

		out.add(readPacket);
	}

	private static String mac(byte[] bs) {
		byte[] temp = new byte[8];
		for (int i = 0; i < temp.length; i++) {
			temp[i] = bs[temp.length - i - 1];
		}

		return ByteUtil.toHex(temp);
	}

	private static byte[] data(byte[] bs) {
		int len = bs.length - 10;

		byte[] temp = new byte[len];
		for (int i = 0; i < temp.length; i++) {
			temp[i] = bs[i + 10];
		}

		return temp;
	}
}
